package com.leetroll.media.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leetroll.api.service.FileService;
import com.leetroll.api.service.ItemService;
import com.leetroll.common.entity.File;
import com.leetroll.common.entity.Item;
import com.leetroll.common.enums.EBucket;
import com.leetroll.common.enums.EFileType;
import com.leetroll.common.utils.AliyunOSSUtil;
import com.leetroll.common.utils.BaiduTranslateUtil;
import com.leetroll.media.utils.FtpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class Job_Temp {

    private final FileService fileService;
    private final ItemService itemService;

    @Autowired
    public Job_Temp(FileService fileService, ItemService itemService) {
        this.fileService = fileService;
        this.itemService = itemService;
    }

    /**
     * 更新库中的item信息 翻译item的名字等
     */
    public void translateItem() {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("id", 2891);
        List<Item> items = itemService.list(queryWrapper);
        items.forEach(item -> {
            String translated = BaiduTranslateUtil.translate(item.getAlias());
            item.setName(translated);
            itemService.updateById(item);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.info("oh what happened");
            }
        });
        log.info("所有item翻译完成");
    }

    /**
     * 已废弃 （迁移ftp服务器的资源到阿里云）
     */
    public void transferFtpFiles() {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "main");
        List<File> files = fileService.list(queryWrapper);
        files.forEach(file -> {
            String fileName = file.getName() + "." + file.getFormat();
            String originalPath = file.getKey() + "/original";
            String smallPath = file.getKey() + "/small";
            ByteArrayOutputStream originalStream = FtpUtil.download(originalPath, fileName);
            ByteArrayOutputStream smallStream = FtpUtil.download(smallPath, fileName);

            if (smallStream == null) {
                fileName = fileName.replace("png", "jpg");
                smallStream = FtpUtil.download(smallPath, fileName);
            }
            if (smallStream == null) {
                fileName = fileName.replace("webp", "jpg");
                smallStream = FtpUtil.download(smallPath, fileName.replace("webp", "jpg"));
            }
            if (smallStream == null) {
                fileName = fileName.replace("gif", "jpg");
                smallStream = FtpUtil.download(smallPath, fileName.replace("gif", "jpg"));
            }
            if (smallStream == null) {
                log.error("*********************{}", fileName);
            }

            String aliOriginalPath = "item/" + file.getRescId() + "/main/original/" + fileName;
            String aliSmallPath = "item/" + file.getRescId() + "/main/small/" + fileName;
            AliyunOSSUtil.upload(aliOriginalPath, new ByteArrayInputStream(originalStream.toByteArray()));
            AliyunOSSUtil.upload(aliSmallPath, new ByteArrayInputStream(smallStream.toByteArray()));

            log.info("上传成功: {}", fileName);
            try {
                originalStream.close();
                smallStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        log.info("******** 任务结束, 共上传{}个文件 ********", files.size());
    }

    /**
     * 重命名阿里云文件名 （更改文件路径）
     */
    public void renameFiles() {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "main");
        queryWrapper.lt("resc_id", 6328);
        List<File> files = fileService.list(queryWrapper);
        for (File file : files) {
            String attaFileName = file.getName() + "." + file.getFormat();
            String prevFileName = file.getName() + ".jpg";

            String prevPath = "item/" + file.getRescId() + "/main/small/" + prevFileName;
            String desPrevPath = "item/" + file.getRescId() + "/main/" + prevFileName;

            String attaPath = "item/" + file.getRescId() + "/main/original/" + attaFileName;
            String desAttaPath = "item/" + file.getRescId() + "/attachment/" + attaFileName;

            AliyunOSSUtil.rename(attaPath, desAttaPath);
            AliyunOSSUtil.rename(prevPath, desPrevPath);

            File attaFile = new File();
            attaFile.setName(file.getName());
            attaFile.setFormat(file.getFormat());
            attaFile.setType(EFileType.ATTACHMENT.getType());
            attaFile.setBucket(EBucket.PRIVATE_BUCKET.getBucket());
            attaFile.setKey("item/" + file.getRescId() + "/attachment/");
            attaFile.setSize(file.getSize());
            attaFile.setRescId(file.getRescId());
            fileService.save(attaFile);

//            file.setFormat("jpg");
//            fileService.updateById(file);

            log.info("重命名成功: {}", file.getRescId());
        }

        log.info("******** 任务结束, 重命名{}个文件 ********", files.size());
    }

    public void updateFile() {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "main");
        List<File> files = fileService.list(queryWrapper);
        files.forEach(file -> {
            file.setKey("item/" + file.getRescId() + "/main/");
        });
        fileService.updateBatchById(files);
        log.info("******** 任务结束 ********");
    }

    /**
     * 重命名本地文件
     */
    public static void renameFile() {
        String path = "F:\\_resources\\sound\\JSE - Melee Weapons\\RECORDINGS\\SCRAPES";
        java.io.File folder = new java.io.File(path);
        for (java.io.File subFolder : folder.listFiles()) {
//            String replaced = subFolder.getName().replace("WINDVege_", "");
//            subFolder.renameTo(new java.io.File(subFolder.getParent() + "\\" +replaced));
//            log.info("");
            if (!subFolder.isDirectory()) continue;
            for (java.io.File file : subFolder.listFiles()) {
                String replaced = file.getName().replace("Friction", "Friction ").replace("_JSE_MW", "");
                file.renameTo(new java.io.File(file.getParent() + "\\" +replaced));
                log.info("");
            }
        }
        log.info("******** 任务结束 ********");
    }

    public static void main(String[] args) {
        renameFile();
    }
}
